package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.EmployeeService;
import com.sky.utils.JwtUtil;
import com.sky.utils.MD5Util;
import io.jsonwebtoken.Claims;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对
        //阿帕奇的MD5加密
       // password = DigestUtils.md5Hex(password);
        //使用MD5加密工具类加密,比对数据库加密后的密码
        password = MD5Util.getMD5Str(password);
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * 新增员工
     * @param employeeDTO
     */
    @Override
    public void insertEmp(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO,employee);
        employee.setPassword(DigestUtils.md5Hex("123456"));
        employee.setCreateTime(LocalDateTime.now());
        employee.setCreateUser(1L);
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(1L);
        employee.setStatus(1);
        employeeMapper.insertEmp(employee);
    }

    /**
     * 分页查询员工,按照name查询员工
     * @param employeePageQueryDTO
     */
    @Override
    public PageResult StaffPaginationSearch(EmployeePageQueryDTO employeePageQueryDTO) {
        if (employeePageQueryDTO.getName()!=null){
            String bfh = "%";
            employeePageQueryDTO.setName(bfh+employeePageQueryDTO.getName()+bfh);
        }
        PageHelper.startPage(employeePageQueryDTO.getPage(),employeePageQueryDTO.getPageSize());
        List<Employee> employees = employeeMapper.StaffPaginationSearch(employeePageQueryDTO);
        Page emp = (Page<Employee>) employees;
        long total = emp.getTotal();
        List<Employee> result = emp.getResult();
        return new PageResult((int)total,result);
    }

    /**
     * 修改员工账号状态
     * @param status
     * @param id
     */
    @Override
    public void ModificationEmpState(String status, Integer id) {
        employeeMapper.ModificationEmpState(status,id);
    }

    /**
     * 根据id查询员工
     * @param id
     * @return
     */
    @Override
    public Employee IDQueryingEmp(String id) {
        Employee employee = employeeMapper.IDQueryingEmp(id);
        return employee;
    }

    /**
     * 修改员工信息
     * @param employeeDTO
     */
    @Override
    public void EditorialStaff(EmployeeDTO employeeDTO) {
        employeeMapper.EditorialStaff(employeeDTO);
    }

    /**
     * 用于修改密码的jwp密钥
     */
    @Value("${sky.jwt.admin-secret-key}")
    public String jwp;

    /**
     * 修改密码
     * @param passwordEditDTO
     * @param request
     * @return
     */
    @Override
    public Result ModificationPassword(PasswordEditDTO passwordEditDTO, HttpServletRequest request) {
        //获取用户id
        String token = request.getHeader("token");
        Claims claims = JwtUtil.parseJWT(jwp,token);
        Long id = claims.get(JwtClaimsConstant.EMP_ID, Long.class);
        passwordEditDTO.setEmpId(id);
        //获取数据库用户密码
        Long empId = passwordEditDTO.getEmpId();
        String aLong = employeeMapper.EmpPassword(empId);

        String newPassword = DigestUtils.md5Hex(passwordEditDTO.getNewPassword());//新密码
        String oldPassword = DigestUtils.md5Hex(passwordEditDTO.getOldPassword());//旧密码

        //判断密码旧密码是否正确
        if (!oldPassword.equals(aLong))
            return Result.error("您输入的旧密码错误");
        //判断旧密码是否和新密码相等
        if (newPassword.equals(aLong))
            return Result.error("旧密码不能于新密码相同");
        //加密新密码
        passwordEditDTO.setNewPassword(newPassword);

        employeeMapper.ModificationPassword(passwordEditDTO);
        return Result.success();
    }
}
